package com.liu.designmode.proxy.utils;

import ch.qos.logback.core.util.StringUtil;
import org.springframework.util.StringUtils;


public class GenericTokenParser {
    // 开始标记 eg: #{
    private String openToken = "#{";

    // 结束标记 eg: }
    private String endToken = "}";


    private ParameterMappingTokenHandler parameterMappingTokenHandler;



    public GenericTokenParser(String openToken, String endToken, ParameterMappingTokenHandler parameterMappingTokenHandler) {
        this.openToken = openToken;
        this.endToken = endToken;
        this.parameterMappingTokenHandler = parameterMappingTokenHandler;
    }

    public String parse(String text) throws Exception {
        if (StringUtils.isEmpty(text)) {
            return "";
        }

        StringBuilder sbd = new StringBuilder();
        int start = text.indexOf(openToken);
        int offset = 0;
        while (start > -1) {
            int end = text.indexOf(endToken, start);
            if (end > -1) {
                sbd.append(text.toCharArray(), offset, start - offset);
                sbd.append("?");
                offset = start + openToken.length();
                String paramName = new String(text.toCharArray(), offset, end - offset);
                // 搜集参数名称，因为传递参数很可能和sql中的顺序是不一致的，所以需要保存sql中的参数顺序
                parameterMappingTokenHandler.addParamName(paramName);
                offset = end + endToken.length();
            } else {
                throw new Exception();
            }
            start = text.indexOf(openToken, offset);
        }
        return sbd.toString();
    }

    public static void main(String[] args) {
        try {
            String text = "select * from user_table where name = #{name} and age = #{age}";
//            System.out.println(new GenericTokenParser().parse(text));
        } catch (Exception e){
            e.printStackTrace();
        }

    }
}
